package com.wx.mythread.threadmethod;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class StudyProducerConsumerModel {

    public static void main(String[] args) {
        EvenStorage storage = new EvenStorage();
        Thread thread1 = new Thread(new Producer(storage));
        Thread thread2 = new Thread(new Consumer(storage));
        thread1.start();
        thread2.start();
    }


    static class Producer implements Runnable{

        private EvenStorage storage;

        public Producer(EvenStorage storage){
            this.storage = storage;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.put();
            }
        }
    }

    static class Consumer implements Runnable{

        private EvenStorage storage;

        public Consumer(EvenStorage storage){
            this.storage = storage;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.take();
            }
        }
    }

    static class EvenStorage {
        private int maxSize;
        private LinkedList<Date> storage;
        public EvenStorage(){
            maxSize = 10;
            storage = new LinkedList<>();
        }

        public synchronized void put(){
            //如果满了我们就等待
            while (storage.size() == maxSize) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //如果没满我们就往里放数据
            storage.add(new Date());
            System.out.println("仓库里有:"+storage.size()+"个产品");
            notify();
        }

        public synchronized void take(){
            while (storage.size() == 0){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //如果没有空，就需要取东西
            System.out.println("拿到了:"+storage.poll()+",现在仓库还剩:"+storage.size());
            notify();
        }
    }
}
